﻿using Microsoft.AspNetCore.Mvc;
using System;
using EasyIot.Model;
using EasyIot.Service;
using EasyIot.WebApp.Controllers;

namespace EasyIot.WebApp.Areas.Permissions.Controllers
{
    public class ItemsDetailController : BaseController
    { 
        // GET: Permissions/ItemsDetail
        public override ActionResult Index(int? id)
        {
            base.Index(id);
            return View();
        }

        [HttpGet]
        public JsonResult List(ItemsDetailModel model, PageInfo pageInfo)
        {
            var result = ItemsDetailService.GetListByFilter(model, pageInfo);
            return Json(result);
        }

        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(ItemsDetailModel model)
        {
            if (ItemsDetailService.IsExistCode(model.ItemCode))
            {
                return Json(ErrorTip("该编码已经存在!"));
            }

            model.CreateTime = DateTime.Now;
            model.CreateUserId = Operator.UserId;
            model.UpdateTime = DateTime.Now;
            model.UpdateUserId = Operator.UserId;
            var result = ItemsDetailService.Insert(model) ? SuccessTip("添加成功") : ErrorTip("添加失败");
            return Json(result);
        }

        public ActionResult Edit(int id)
        {
            var model = ItemsDetailService.GetById(id);
            model.ItemCode_EditBefore = model.ItemCode;
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(ItemsDetailModel model)
        {
            if (!model.ItemCode_EditBefore.Trim().ToLower().Equals(model.ItemCode.Trim().ToLower()) && ItemsDetailService.IsExistCode(model.ItemCode))
            {
                return Json(ErrorTip("该编码已经存在!"));
            }

            model.UpdateTime = DateTime.Now;
            model.UpdateUserId = Operator.UserId;
            var result = ItemsDetailService.UpdateById(model) ? SuccessTip("修改成功") : ErrorTip("修改失败");
            return Json(result);
        }

        [HttpGet]
        public JsonResult Delete(int id)
        {
            var result = ItemsDetailService.DeleteById(id) ? SuccessTip("删除成功") : ErrorTip("删除失败");
            return Json(result);
        }


        [HttpGet]
        public JsonResult BatchDel(string idsStr)
        {
            var idsArray = idsStr.Substring(0, idsStr.Length - 1).Split(',');
            var result = ItemsDetailService.DeleteByIds(idsArray) ? SuccessTip("批量删除成功") : ErrorTip("批量删除失败");
            return Json(result);
        }
    }
}